package com.lw.leetcode.other.b;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *166. 分数到小数
 * @author liw
 * @version 1.0
 * @date 2021/11/2 11:18
 */
public class FractionToDecimal {

    public String fractionToDecimal(int numerator, int denominator) {
        if (numerator == 0) {
            return "0";
        }
        long a = numerator;
        long b = denominator;
        boolean flag = false;
        if (a < 0) {
            flag = true;
            a *= (-1);
        }
        if (b < 0) {
            flag = !flag;
            b *= (-1);
        }
        StringBuilder sb = new StringBuilder();
        if (flag) {
            sb.append("-");
        }
        sb.append(a / b);
        long item = a % b * 10;
        if (item == 0) {
            return sb.toString();
        }
        sb.append('.');
        Map<Long, Integer> map = new HashMap<>();
        int index = sb.length();
        while (item != 0L && map.get(item) == null) {
            map.put(item, index);
            sb.append(item / b);
            item = item % b * 10;
            index++;
        }
        if (item == 0L) {
            return sb.toString();
        } else {
            index = map.get(item);
            return sb.substring(0, index) + "(" + sb.substring(index) + ")";
        }
    }

}
